<template>
  <el-dialog :title="formData.id ? '编辑分类' : '添加分类'" :visible="dialogVisible" @close="closeFn">
    <el-form ref="form" :model="formData" status-icon :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" autocomplete="off" />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input v-model="formData.desc" autocomplete="off" />
      </el-form-item>
      <el-form-item label="封面" prop="image">
        <!-- 图片上传 -->
        <ImageUploader ref="picture" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-row>
        <el-col>
          <el-button size="small" @click="closeFn">取消</el-button>
          <el-button size="small" type="primary" @click="confirmFn">确定</el-button>
        </el-col>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import { addCategory, editCategory, getCategoryById } from '@/api/category'
export default {
  props: {
    dialogVisible: { type: Boolean, require: true },
    id: { type: Number }
  },
  data() {
    return {
      title: ['添加分类', '编辑分类'],
      rules: {
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        desc: [{ required: true, message: '描述不能为空', trigger: 'blur' }]
      },
      formData: {
        title: '',
        desc: '',
        image: ''
      }
    }
  },
  created() {},
  methods: {
    // 获取分类详情进行回显
    async getCategoryById() {
      const res = await getCategoryById(this.id)
      this.formData = res.data
      this.$refs.picture.fileList = []
      this.$refs.picture.fileList.push({ url: this.formData.image })
      this.formData.id = this.id
    },
    closeFn() {
      this.$emit('update:dialogVisible', false)
      this.$refs.picture.fileList = []
      this.formData = {
        title: '',
        desc: '',
        image: ''
      }
      this.$refs.form.resetFields()
    },
    async confirmFn() {
      this.formData.image = this.$refs.picture.fileList[0].url // 上传的封面地址
      await this.$refs.form.validate()
      if (this.formData.id) {
        await editCategory(this.formData) // 编辑分类
      } else {
        await addCategory(this.formData)
      } // 发起添加分类请求
      this.$emit('updateCategories') // 刷新列表

      this.closeFn()
    }
  }
}
</script>

<style></style>
